const utils = require('./utils');

const domAddDoc = async function (dom, pObj, docxFile, filePath) {
  return new Promise(async (resolve) => {
    if (Array.isArray(dom)) {
      for (let i = 0; i < dom.length; i++) {
        await domItemAnalysis(dom[i], pObj, docxFile, filePath);
        resolve();
      }
    } else {
      await domItemAnalysis(dom, pObj, docxFile, filePath);
      resolve();
    }
  });
};

const domItemAnalysis = async function (dom, pObj, docxFile, filePath) {
  return new Promise(async (resolve) => {
    if (dom.prev && dom.prev.type === 'tag' && dom.prev.name === 'p') {
      pObj.addText('\n');
    }
    if (dom.type === 'text') pObj.addText(dom.data);
    if (dom.type === 'tag' && dom.name === 'img') {
      await utils.downloadImage(dom.attribs.src, filePath, docxFile, pObj);
    }
    if (dom && dom.children && dom.children.length > 0) {
      await domAddDoc(dom.children, pObj, docxFile, filePath);
    }
    resolve();
  });
};

module.exports = {
  domAddDoc,
};
